const connection = require("../db");
const { courseData, bizCourseAttachments } = require("../data/courseList");
const fs = require("fs");
const path = require("path");
const { v4: uuidv4 } = require("uuid");

const getCourse = (req, res, next) => {
  const sql = "SELECT * FROM tb_course";
  //查
  connection.query(sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    console.log(result);

    return res.json({ success: true, code: 1, data: result });
  });
};

const getGoodsCourse = (req, res, next) => {
  const sql = "SELECT * FROM tb_good_books";
  connection.query(sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    console.log(result);

    return res.json({ success: true, code: 1, data: result });
  });
};

const addCourses = (req, res, next) => {
  var addSql = "INSERT INTO websites(name,url,alexa,country) VALUES(?,?,?,?)";
  var addSqlParams = ["菜鸟工具", "https://c.runoob.com", "23453", "CN"];
  connection.query(addSql, addSqlParams, function (err, result) {
    if (err) {
      console.log("[INSERT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "新增失败" });
    }

    console.log("--------------------------INSERT----------------------------");
    console.log("INSERT ID:", result);
    console.log(
      "-----------------------------------------------------------------\n\n"
    );
    return res.json({ success: true, code: 1, msg: "新增成功" });
  });
};

const getCourseType = (req, res, next) => {
  const sql = "SELECT * FROM tb_course_type";
  connection.query(sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    console.log(result);

    return res.json({ success: true, code: 1, data: result });
  });
};

const getCourseCatagory = (req, res, next) => {
  console.log("🚀 ~ getCourseCatagory ~ req:", req.query);
  const sql = `SELECT * FROM tb_course_catagory where course_type = ${req.query.id}`;
  const allSql = "SELECT * FROM tb_course_catagory";

  connection.query(req.query.id == 0 ? allSql : sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    console.log(result);

    return res.json({ success: true, code: 1, data: result });
  });
};

const getCourseLevel = (req, res, next) => {
  console.log("🚀 ~ getCourseCatagory ~ req:", req.query);
  const sql = `SELECT * FROM tb_course_catagory where level = ${req.query.levelId} and course_catagory = ${req.query.courseCatagoryId}`;
  const allSql = "SELECT * FROM tb_course_catagory";

  connection.query(req.query.id == -1 ? allSql : sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    console.log(result);
    console.log(
      "------------------------------------------------------------\n\n"
    );
    return res.json({ success: true, code: 1, data: result });
  });
};

// 分页查询

const getCourseByPage = (req, res, next) => {
  const { data } = req.body;
  // 分页参数
  const page = data.page || 1; // 当前页数
  const limit = data.pageSize || 10; // 每页显示数量
  const offset = (page - 1) * limit; // 计算偏移量
  const catagoryId = data.catagoryId; // 分类id
  const levelId = data.levelId; // 等级id
  const courseType = data.typeId; // 课程类型
  let query = "";
  const isAll = catagoryId === 0 && levelId === 0 && courseType === 0; // 是否查询全部
  const isCourseType = courseType !== 0 && levelId === 0 && catagoryId === 0;
  const isCatagoryType = courseType !== 0 && catagoryId !== 0 && levelId === 0;
  const isLevelType = catagoryId !== 0 && levelId !== 0 && courseType !== 0;

  if (isAll) {
    query = `SELECT * FROM tb_course limit ${limit} offset ${offset}`;
  } else if (isCourseType) {
    query = `SELECT * FROM tb_course where course_type = ${courseType} limit ${limit} offset ${offset}`;
  } else if (isCatagoryType) {
    query = `SELECT * FROM tb_course where course_type = ${courseType} and course_catagory = ${catagoryId} limit ${limit} offset ${offset}`;
  } else if (isLevelType) {
    query = `SELECT * FROM tb_course where course_level = ${levelId} and course_type= ${courseType} and course_catagory = ${catagoryId} limit ${limit} offset ${offset}`;
  }

  // 执行分页查询
  connection.query(query, async (error, result) => {
    console.log("🚀 ~ getCourseByPage ~ query:", query);
    if (error) {
      return res.json({ success: true, code: 0, msg: "查询失败" });
    }

    let mysql = "";
    if (isAll) {
      mysql = `SELECT count(*) as total  FROM tb_course`;
    } else if (isCourseType) {
      mysql = `SELECT count(*) as total FROM tb_course where course_type = ${courseType}`;
    } else if (isCatagoryType) {
      mysql = `SELECT count(*) as total FROM tb_course where course_type= ${courseType} and course_catagory = ${catagoryId}`;
    } else if (isLevelType) {
      mysql = `SELECT count(*) as total FROM tb_course where course_level = ${levelId} and course_type= ${courseType} and course_catagory = ${catagoryId}`;
    }

    connection.query(mysql, (err, res1) => {
      console.log("🚀 ~ res1 ~ res1:", res1);
      if (err) {
        return res.json({ success: true, code: 0, msg: "查询失败" });
      } else {
        return res.json({
          success: true,
          code: 1,
          data: {
            total: res1[0]?.total || 0,
            list: result,
            page: data.page,
            pageSize: data.pageSize,
          },
        });
      }
    });
  });
};

const getCourseChapts = (req, res, next) => {
  console.log(uuidv4, "uuid");
  return res.json({
    success: true,
    code: 1,
    data: {
      courseId: uuidv4(),
      bizCourseDetail:
        "前端技术专家老师带你系统构建 React18 技术体系，并结合“欢乐购”项目，快速积累企业级前端项目实战经验，落地 React18 与 TypeScript 结合的实用开发技巧。同时老师分享了React框架核心源码实现原理的深度思考，进一步帮助大家 “学懂用活”，真正走近框架，全面提升技术实力",
      courseData,
      courseName: "React18+TypeScript实战开发",
      courseLevel: 2,
      bizCourseAttachments,
    },
  });
};

//下载资料
const imagePath = (name) => path.join(__dirname, `../public/images/${name}`);
const downloadFile = (req, res, next) => {
  // console.log("🚀 ~ fs.readFile ~ imagePath:", req.query.name);
  const nameArr = req.query.name.split("/");
  fs.readFile(imagePath(nameArr[nameArr.length - 1]), (err, buffer) => {
    if (err) {
      res.status(500).send("Error reading image");
      return;
    }
    // 设置响应头
    switch (req.query.name) {
      case "pdf":
        res.setHeader("Content-Type", "application/pdf");
        break;
      default:
        res.setHeader("Content-Type", "image/jpeg");
    }

    // 设置响应头
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      `attachment; filename=${encodeURIComponent(nameArr[nameArr.length - 1])}`
    );

    // 发送图片数据
    res.send(buffer);
  });
};

module.exports = {
  getCourse,
  getGoodsCourse,
  addCourses,
  getCourseType,
  getCourseCatagory,
  getCourseLevel,
  getCourseByPage,
  getCourseChapts,
  downloadFile,
};
